﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Web;
using System.Configuration;
using EntityLibrary;
using DALLibrary;
using RazorEngine;

namespace CreatePageLibrary
{
    public class CreatePage
    {
        /// <summary>
        /// 模板名称
        /// </summary>
        private string TemplateName = ConfigurationManager.AppSettings["TemplateName"].ToString().Trim();
        /// <summary>
        /// 生成文件的路径
        /// </summary>
        private string CreatePath = ConfigurationManager.AppSettings["CreatePagePath"].ToString().Trim();


        /// <summary>
        /// 生成文件
        /// </summary>
        /// <param name="id"></param>
        public void CreatePageFile(int id)
        {
            PageControl pageCtl = new PageControl();
            PageConfig config = pageCtl.GetPageControlList(id);
            string template = File.ReadAllText(HttpContext.Current.Server.MapPath(TemplateName));
            foreach (PageConfig_Step step in config.ProcessStep) //对步骤做循环生成页面
            {
                if (step.StepControl.Count > 0)
                {
                    List<PageConfig_Control> buttons = step.StepControl.FindAll(p => p.Control.ToUpper().IndexOf("BUTTON") >= 0
                        && p.Control.ToUpper().IndexOf("RADIOBUTTON") < 0 && p.ControlEName.ToUpper().IndexOf("TABLE")<0);
                    List<PageConfig_Control> Controls = step.StepControl.FindAll(p =>( p.Control.ToUpper().IndexOf("BUTTON") < 0
                        || p.Control.ToUpper().IndexOf("RADIOBUTTON") >= 0 ) && p.ControlEName.ToUpper().IndexOf("TABLE") < 0);
                    List<PageConfig_Control> grid = step.StepControl.FindAll(p => p.ControlEName.ToUpper().IndexOf("TABLE") >= 0);
                    List<string> grids = new List<string>();
                    foreach (PageConfig_Control ctl in grid)
                    {
                        if (!grids.Contains(ctl.TableName))
                        {
                            grids.Add(ctl.TableName);
                        }
                    }
                    string result = Razor.Parse(template,
                   new
                   {
                       ProcessName = config.ProcessName
                       ,
                       StepName = step.StepName
                       ,
                       Controls = Controls,
                       Buttons = buttons,
                       Grids = grids
                   });
                    string path = HttpContext.Current.Server.MapPath(CreatePath);
                    File.WriteAllText(path + "\\" + step.StepID + ".aspx", result, System.Text.Encoding.UTF8);
                }
            }


        }


    }
}
